package com.work.yshop.mvp.presenter;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.work.yshop.mvp.model.HomeModel;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 首页的Presenter实现
 */
public class HomePresenter implements HomeContract.Presenter {
    private static final String TAG = "HomePresenter";
    
    private WeakReference<HomeContract.View> viewRef;
    private Context context;
    private HomeModel model;
    private List<Product> allProducts;
    private List<Product> currentCategoryProducts;
    private int currentPage = 1;
    private int pageSize = 10;
    private int currentCategory = 0;
    private boolean isLoading = false;
    
    // 分类名称数组
    private final String[] categories = {"推荐", "水果", "粮油", "工具", "特产", "畜牧"};
    
    // 模拟延迟
    private final Handler handler = new Handler(Looper.getMainLooper());
    
    public HomePresenter(Context context) {
        this.context = context;
        this.model = new HomeModel(context);
        this.allProducts = new ArrayList<>();
        this.currentCategoryProducts = new ArrayList<>();
    }

    @Override
    public void attachView(HomeContract.View view) {
        viewRef = new WeakReference<>(view);
    }

    @Override
    public void detachView() {
        if (viewRef != null) {
            viewRef.clear();
            viewRef = null;
        }
    }

    @Override
    public void getRecommendProducts() {
        if (getView() == null) return;
        
        currentCategory = 0;
        currentPage = 1;
        getView().showLoading();
        
        // 使用AsyncTask从数据库加载数据
        new AsyncTask<Void, Void, List<Product>>() {
            @Override
            protected List<Product> doInBackground(Void... voids) {
                // 从数据库获取所有商品
                List<Product> products = model.getAllProducts();
                Log.d(TAG, "从数据库加载商品: " + products.size() + " 条");
                if (products.isEmpty()) {
                    // 如果数据库为空，则使用统一的模拟数据源
                    products = ProductDataUtils.getMockProductData();
                }
                return products;
            }
            
            @Override
            protected void onPostExecute(List<Product> products) {
                if (getView() == null) return;
                
                allProducts = products;
                currentCategoryProducts = new ArrayList<>(allProducts);
                
                if (currentCategoryProducts.isEmpty()) {
                    getView().showEmpty();
                } else {
                    getView().showProducts(currentCategoryProducts);
                }
                
                getView().hideLoading();
            }
        }.execute();
    }

    @Override
    public void getProductsByCategory(int categoryId) {
        if (getView() == null) return;
        
        currentCategory = categoryId;
        currentPage = 1;
        getView().showLoading();
        
        // 使用AsyncTask从数据库加载数据
        new AsyncTask<Integer, Void, List<Product>>() {
            @Override
            protected List<Product> doInBackground(Integer... params) {
                int categoryId = params[0];
                List<Product> products;
                
                if (categoryId == 0) {
                    // 推荐分类，获取所有商品
                    products = model.getAllProducts();
                } else {
                    // 根据分类获取商品
                    String categoryName = categories[categoryId];
                    products = model.getProductsByCategory(categoryName);
                    
                    // 如果该分类没有商品，作为备选方案根据ID模拟筛选
                    if (products.isEmpty() && !allProducts.isEmpty()) {
                        products = allProducts.stream()
                            .filter(product -> product.getId() % 6 == categoryId % 6)
                            .collect(Collectors.toList());
                    }
                }
                
                // 如果数据库为空，使用统一的模拟数据
                if (products.isEmpty()) {
                    products = ProductDataUtils.getMockProductData();
                    if (categoryId > 0) {
                        // 根据分类筛选
                        final int filterCategoryId = categoryId;
                        products = products.stream()
                            .filter(product -> product.getId() % 6 == filterCategoryId % 6)
                            .collect(Collectors.toList());
                    }
                }
                
                Log.d(TAG, "分类 " + categoryId + " 加载商品: " + products.size() + " 条");
                return products;
            }
            
            @Override
            protected void onPostExecute(List<Product> products) {
                if (getView() == null) return;
                
                currentCategoryProducts = products;
                
                if (currentCategoryProducts.isEmpty()) {
                    getView().showEmpty();
                } else {
                    getView().showProducts(currentCategoryProducts);
                }
                
                getView().hideLoading();
            }
        }.execute(categoryId);
    }

    @Override
    public List<Product> getAllProducts() {
        return allProducts;
    }

    @Override
    public List<Product> searchProducts(String keyword) {
        if (keyword == null || keyword.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 从所有商品中搜索包含关键词的商品
        return allProducts.stream()
            .filter(product -> 
                product.getName().toLowerCase().contains(keyword.toLowerCase()) || 
                (product.getDescription() != null && product.getDescription().toLowerCase().contains(keyword.toLowerCase())))
            .collect(Collectors.toList());
    }

    @Override
    public void loadMoreProducts() {
        if (getView() == null || isLoading) return;
        
        isLoading = true;
        
        // 模拟加载更多数据
        handler.postDelayed(() -> {
            // 使用统一的数据源加载更多数据
            List<Product> moreProducts = ProductDataUtils.createMoreProductData();
            
            // 添加到当前分类的商品列表
            currentCategoryProducts.addAll(moreProducts);
            
            // 添加到所有商品列表
            allProducts.addAll(moreProducts);
            
            if (getView() != null) {
                getView().showProducts(currentCategoryProducts);
            }
            
            currentPage++;
            isLoading = false;
        }, 1000);
    }
    
    /**
     * 获取当前绑定的View
     */
    private HomeContract.View getView() {
        return viewRef != null ? viewRef.get() : null;
    }
} 